package it.progettoso.thread;


import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.HandlerThread;
import android.provider.Settings;
import android.telephony.SmsManager;
import android.widget.Toast;

public class GPSLocationThread implements Runnable{
	
	protected String mess="";
	protected double Lat=0.0D,Long=0.0D;
	
	
	private Context c;
	private String phone;
	private LocationManager lm;
	private LocationListener locationListener;
	private HandlerThread mthread;
	AudioManager manager=null;
	
	public GPSLocationThread(Context context, String phone, HandlerThread mthread){
		this.phone=phone;
		this.c=context;
		this.mthread=mthread;
		lm = (LocationManager)c.getSystemService(Context.LOCATION_SERVICE); 
		locationListener = new MyLocationListener();
	}
	
	@Override
	public void run() {
		
		if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
			turnGPSOn();

		while(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){}		
		
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,10,locationListener);
		
		
	}

	private class MyLocationListener implements LocationListener
	{
		@Override
		public void onLocationChanged(Location loc) {
			
			if (loc != null) {
				Toast.makeText(c, "OnLocationChanged\n Lat: "+loc.getLatitude() + "Long: "+loc.getLongitude(), Toast.LENGTH_SHORT).show();
				Lat=loc.getLatitude();
				Long=loc.getLongitude();
				mess="Info GPS: Latitudine: "+loc.getLatitude() 
				+ " Longitudine: "+loc.getLongitude();
				sendSMS(phone, mess);
				mthread.getLooper().quit();
			}else{
				Toast.makeText(c,"Location NULL", Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
			turnGPSOn();
		}

		@Override
		public void onProviderEnabled(String provider) {

		}

		@Override
		public void onStatusChanged(String provider, int status,
				Bundle extras) {
		}
	} 

	//---sends a SMS message to another device---
	public void sendSMS(String phoneNumber, String message){      
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, null, null);               
	}  
	
	private void turnGPSOn(){  
		String provider = Settings.Secure.getString(c.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);   
		if(!provider.contains("gps")){      
			final Intent poke = new Intent();  
			poke.setClassName("com.android.settings","com.android.settings.widget.SettingsAppWidgetProvider");
			poke.addCategory(Intent.CATEGORY_ALTERNATIVE);   
			poke.setData(Uri.parse("3"));      
			c.sendBroadcast(poke); 
		} 
	}

}
